import {Component, OnInit, ViewChild} from '@angular/core';
import {AppService} from '../../app.service';
import {CommonTool} from '../../common/common.tool';
import {environment} from '../../../environments/environment';
import {ActivatedRoute, Router} from '@angular/router';
import {TableFindModel} from '../../common/table-find/table-find.model';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {FileManagementService} from '../file-management/file-management.service';
import {HomeService} from '../home.service';
import Viewer from 'viewerjs';
import {MusicPlayerComponent} from '../../common/music-player/music-player.component';
import {BasicService} from '../../basic/basic.service';
import {DictService} from '../../common/service/dict.service';
import {CreateFolderComponent} from '../file-management/create-folder/create-folder.component';

@Component({
  selector: 'app-file-management',
  templateUrl: './share-file.component.html',
  styleUrls: ['./share-file.component.scss']
})
export class ShareFileComponent implements OnInit {
  @ViewChild(MusicPlayerComponent, {static: true})
  public musicPlayerComponent: MusicPlayerComponent;
  public videoPlay = {url: '', isVisible: false};
  public showMusicPlay = false;
  public pictureFiles: Array<any>;
  // 保存弹框
  public selectFolder = {folderId: '', isVisible: false, type: '', okText: '保存'};

  // 授权码
  public isDrawCodeVisible = false;
  public drawCode = '';

  // 共享id和父级id
  public shareId;
  public folderId;
  public userId;
  public currentUser;
  public visitCode;

  // 文件目录配置
  public COMMON_TYPE;
  public tableFindModel: TableFindModel;
  public tableFindModel1: TableFindModel;
  public viewer;
  public imgConfig = {};
  public code;
  public recommendMovie: Array<{ name, value }> = [];
  public compressUrl = '?open=0&w=30&h=50';
  public compressUrl1 = '?open=0';
  @ViewChild(CreateFolderComponent, {static: true})
  public createFolderComponent: CreateFolderComponent;

  constructor(public fileManagementService: FileManagementService,
              private router: Router,
              private homeService: HomeService,
              public activateRoute: ActivatedRoute,
              public basicService: BasicService,
              public modalService: NzModalService,
              public appService: AppService,
              private message: NzMessageService,
              public dictService: DictService,
              public activatedRoute: ActivatedRoute) {
    this.tableFindModel = new TableFindModel();
    this.tableFindModel1 = new TableFindModel();
    this.COMMON_TYPE = TableFindModel.COMMON_TYPE;
    this.folderId = 'root';
    this.code = this.activatedRoute.snapshot.params['code'];
    const param = CommonTool.getUrlParam(location.href);
    const token = CommonTool.getCookie(environment.tokenKey);
    if (param['code'] && !token) {
      const state = localStorage.getItem('state');
      if (param['state'] === state) {
        this.basicService.getToken(param['code'], null).subscribe(res => {
          let authorityCodes = res['authorityCodes'];
          authorityCodes = authorityCodes.concat(res['groupAuthorityCodes']);
          if (!authorityCodes || authorityCodes.length === 0) {
            this.modalService.info({
              nzTitle: '你没有访问该系统的权限！',
              nzContent: '<p>已向管理员申请，请联系该系统管理员！</p><p>用户账号：<b>' + res['account'] + '</b></p>',
              nzOkText: '确认',
              nzOnOk: () => {
                this.basicService.jumpLogin();
              }
            });
          } else {
            this.basicService.initLogin(res, authorityCodes, () => {
              // 查询用户信息
              this.homeService.getMyAppUser().subscribe(user => {
                this.currentUser = user;
                this.initFun();
              });
            });
          }
        }, error => {
          this.basicService.jumpLogin();
        });
      } else {
        this.basicService.jumpLogin();
      }
    } else {
      if (token) {
        let authorityCodes = JSON.parse(localStorage.getItem(environment.authorityKey));
        if (!authorityCodes) {
          authorityCodes = [];
        }
        this.basicService.initLogin(JSON.parse(token), authorityCodes, () => {
          this.homeService.getMyAppUser().subscribe(res => {
            this.currentUser = res;
            this.initFun();
          });
        });
      } else {
        this.initFun();
      }
    }
  }

  // 初始化
  ngOnInit(): void {
    const that = this;
    if (window.history && window.history.pushState) {
      window.onpopstate = (e) => {
        const url = decodeURI(e['target']['location'].href);
        const data = CommonTool.getUrlParam(url);
        if (data['folderId']) {
          that.tableFindModel.getData({folderId: data['folderId']}, null);
        } else {
          that.tableFindModel.getData({folderId: null}, null);
        }
      };
    }
  }

  /**
   * 登录成功回调
   */
  public initFun() {
    // 获取字典信息
    this.dictService.getCacheAndDictListByType('fileIcon').subscribe(res => {
      for (const dict of res) {
        this.imgConfig[dict.name] = dict.value;
      }
    });
    this.dictService.getCacheAndDictListByType('recommendMovie').subscribe(res => {
      this.recommendMovie = res;
    });
    const share = JSON.parse(localStorage.getItem(this.code));
    if (CommonTool.notNull(share)) {
      this.shareId = share.shareId;
      this.userId = share.userId;
      this.visitCode = share.visitCode;
      this.getShareParentFolderList();
    } else {
      this.fileManagementService.verifyShareCode(this.code).subscribe(res => {
        if (!res['needDrawCode']) {
          localStorage.setItem(this.code, JSON.stringify(res));
          this.userId = res.userId;
          this.shareId = res.shareId;
          this.visitCode = res.visitCode;
          this.getShareParentFolderList();
        } else {
          this.isDrawCodeVisible = true;
        }
      });
    }
  }

  /**
   * 验证提取码
   */
  public verifyDrawCode() {
    const code = this.activatedRoute.snapshot.params['code'];
    this.fileManagementService.verifyShareCode(code, this.drawCode).subscribe(res => {
      if (CommonTool.notNull(res)) {
        this.isDrawCodeVisible = false;
        localStorage.setItem(code, JSON.stringify(res));
        this.shareId = res.shareId;
        this.userId = res.userId;
        this.visitCode = res.visitCode;
        this.getShareParentFolderList();
      }
    });
  }

  /**
   * 获取labels
   */
  public getShareParentFolderList() {
    const folderId = this.activateRoute.snapshot.queryParams['folderId'];
    if (folderId) {
      this.fileManagementService.getShareParentFolderList(this.shareId, folderId).subscribe(folders => {
        this.init(folderId, folders);
      });
    } else {
      this.init(folderId, []);
    }
  }

  /**
   * 初始化
   */
  public init(folderId, folders) {
    const COMMON_TYPE = TableFindModel.COMMON_TYPE;
    const myThis = this;
    const labels = [{name: '全部', folderId: ''}];
    for (const folder of folders) {
      labels.push({
        name: folder.name,
        folderId: folder.id
      });
    }
    this.tableFindModel.initAll({
      finds: [
        {
          name: '文件名',
          field: 'name',
          input: {
            maxLength: 255
          }
        }
      ],
      buttons: [
        {
          name: '首页',
          field: 'home',
          type: COMMON_TYPE.button.BUTTON,
          confirmFun: () => {
            myThis.router.navigateByUrl('/home');
          }
        },
        {
          name: '登录', field: 'login', type: COMMON_TYPE.button.BUTTON, confirmFun: () => {
            const state = Math.ceil(Math.random() * 100000);
            const redirectUri = escape(location.origin + '/#/share/' + this.code);
            location.href = environment.config.loginUrl + '&redirectUri=' + redirectUri + '&state=' + state;
            localStorage.setItem('state', state + '');
          }
        },
        {
          name: '保存到网盘', field: 'save', type: COMMON_TYPE.button.BUTTON,
          disabledFun: () => {
            let bool = true;
            myThis.tableFindModel.dataModels.forEach(dataModel => {
              if (dataModel.selected) {
                bool = false;
              }
            });
            return bool;
          },
          confirmFun: () => {
            myThis.selectFolder = {folderId: '', isVisible: true, type: 'copy', okText: '保存'};
            myThis.tableFindModel1 = myThis.fileManagementService.selectFolder(myThis.imgConfig, myThis.createFolderComponent, (label) => {
              myThis.selectFolder.folderId = label.folderId;
            }, {isMyOf: true});
          }
        },
        {
          name: '退出登录', field: 'logOut', type: COMMON_TYPE.button.BUTTON,
          confirmFun: () => {
            CommonTool.deleteCookie(environment.tokenKey);
            myThis.isLogin();
          }
        }
      ],
      breadcrumb: {
        breadcrumbFun: (label, i, that) => {
          if (i + 1 < labels.length) {
            labels.splice(i + 1, labels.length);
          }
          that.getData({folderId: labels[i].folderId}, null);
        },
        labels: [] // 面包屑
      },
      tables: [
        {name: '', field: 'checkbox', type: COMMON_TYPE.table.CHECKBOX},
        {
          name: '', field: 'imageUrl', type: COMMON_TYPE.table.IMAGE,
          tdStyle: {cursor: 'pointer'},
          initFun(dataModel, that) {// dataModel：初始化的数据，that:当前对象
            if (dataModel['isFile']) {
              // 获取后缀
              const suffix = CommonTool.getSuffix(dataModel.data.name);
              if (myThis.fileManagementService.verifyImageSuffix(suffix)) {
                dataModel.data['imageUrl'] = dataModel.data['url'] + myThis.compressUrl;
                myThis.pictureFiles.push(dataModel.data);
              } else {
                const i = dataModel.data.name.lastIndexOf('.');
                const fileSuffix = dataModel.data.name.substring(i + 1, dataModel.data.name.length);
                if (myThis.imgConfig['disk_file_icon_' + fileSuffix]) {
                  dataModel.data['imageUrl'] = myThis.imgConfig['disk_file_icon_' + fileSuffix];
                } else {
                  dataModel.data['imageUrl'] = myThis.imgConfig['disk_icon_file'];
                }
              }
            }
          },
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              const label = {name: dataModel.data.name, folderId: dataModel.data.id};
              labels.push(label);
              that.getData({folderId: dataModel.data.id}, null);
            } else {
              myThis.openFile(dataModel.data);
            }
          }
        },
        {
          name: '文件名',
          field: 'name',
          type: COMMON_TYPE.table.TITLE,
          isSort: true,
          tdStyle: {cursor: 'pointer'},
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              const label = {name: dataModel.data.name, folderId: dataModel.data.id};
              labels.push(label);
              that.getData({folderId: dataModel.data.id}, null);
            } else {
              myThis.openFile(dataModel.data);
            }
          }
        },
        {
          name: '', field: 'createTime', type: COMMON_TYPE.table.DESCRIPTION,
          confirmFun: (dataModel, table, that) => {
            if (!dataModel['isFile']) {
              const label = {name: dataModel.data.name, folderId: dataModel.data.id};
              labels.push(label);
              that.getData({folderId: dataModel.data.id}, null);
            }
          }
        },
        {
          name: '', field: 'size', type: COMMON_TYPE.table.DESCRIPTION,
          tdStyle: {cursor: 'pointer'},
          confirmFun: (dataModel) => {
            if (!dataModel['isFile']) {
              if (dataModel.data['size'] === '计算') {
                myThis.fileManagementService.getShareFolderSize(myThis.shareId, dataModel.data['id']).subscribe(res => {
                  dataModel.data['size'] = CommonTool.getSpace(res.size);
                });
              }
            }
          }
        },
        {
          name: '', field: '', type: COMMON_TYPE.table.OPERATE,
          initFun(dataModel, that) {// data：初始化的数据，that:全局this
            if (!dataModel['isFile']) {
              dataModel['cdn'] = false;
              dataModel['download'] = false;
            }
          },
          operates: [
            {
              name: '下载', field: 'download', confirmFun(dataModel, that) {
                if (dataModel.data['url']) {
                  location.href = dataModel.data['url'];
                } else {
                  location.href = dataModel.data['url'];
                }
              }
            }
          ]
        }
      ],
      initDataFun: (formInfo, sortPage, callback, that) => {// 数据处理回调 config：配置，dataModels：数据，that：当前对象
        const req = {
          sortField: sortPage.sortField,
          sortRule: sortPage.sortRule,
          likeFields: ['name'],
          visitCode: myThis.visitCode,
          folderId: formInfo['folderId']
        };
        for (const find of that.config.finds) {
          req[find.field] = formInfo[find.field];
        }
        myThis.fileManagementService.getShareFolderFile(req).subscribe(res => {
          const array = [];
          myThis.pictureFiles = [];
          // 处理目录数据
          for (const arr of res['folders']) {
            arr.size = '计算';
            arr['imageUrl'] = myThis.imgConfig['disk_icon_folder'];
            array.push({data: arr, isFile: false});
          }
          // 处理文件数据
          for (const arr of res['files']) {
            arr.size = CommonTool.getSpace(arr.size);
            array.push({
              data: arr,
              isFile: true
            });
          }
          // 生成labels
          that.config.breadcrumb.labels = labels;
          // 跳转记录
          const code = myThis.activatedRoute.snapshot.params['code'];
          if (formInfo['folderId'] !== null) {
            const url = CommonTool.analysisParam('/share/' + code, {folderId: formInfo['folderId']});
            myThis.router.navigateByUrl(url);
          } else {
            myThis.router.navigateByUrl('/share/' + code);
          }
          callback(array, {size: array.length});
        });
      },
      openPaging: false,
      frontSort: false
    }, null, {folderId});
    this.isLogin();
  }

  /**
   * 确认创建弹窗
   */
  public createFolderOk() {
    this.tableFindModel1.getData(null, null);
  }

  /**
   * 打开文件
   */
  public openFile(data) {
    const suffix = CommonTool.getSuffix(data.name);
    if (suffix === '.mp3') {
      this.handleMp3(data.id);
    } else if (data['url']) {
      this.handleFile(data);
    } else {
      this.handleFile(data);
    }
  }

  /**
   * 处理mp3
   */
  public handleMp3(id) {
    this.musicPlayerComponent.setPlayList([]);
    this.tableFindModel.dataModels.forEach((ref) => {
      const suffix = CommonTool.getSuffix(ref.data['name']);
      if (suffix === '.mp3' && !ref.data['url']) {
        const playId = this.musicPlayerComponent.addMusic({
          name: ref.data['name'],
          url: ref.data['url']
        });
        if (id === ref.data['id']) {
          this.showMusicPlay = true;
          this.musicPlayerComponent.play(playId);
        }
      } else if (suffix === '.mp3') {
        const playId = this.musicPlayerComponent.addMusic({
          name: ref.data['name'],
          url: ref.data['url']
        });
        if (id === ref.data['id']) {
          this.showMusicPlay = true;
          this.musicPlayerComponent.play(playId);
        }
      }
    });
  }

  /**
   * 处理文件
   */
  public handleFile(data) {
    const that = this;
    const suffix = CommonTool.getSuffix(data.name);
    if (suffix === '.mp4') {
      this.videoPlay.isVisible = true;
      this.videoPlay.url = data['url'];
    } else if (this.fileManagementService.verifyImageSuffix(suffix)) {
      if (!this.viewer) {
        this.viewer = new Viewer(document.getElementById('image'), {
          initialViewIndex: 0,
          url(image) {
            return image.src.split('?')[0] + that.compressUrl1;
          }
        });
      } else {
        this.viewer.update();
      }
      for (let i = 0; i < this.pictureFiles.length; i++) {
        if (data['id'] === this.pictureFiles[i]['id']) {
          this.viewer.view(i);
        }
      }
      this.viewer.show();
    }
  }

  /**
   * 检测是否登录
   */
  public isLogin() {
    const token = CommonTool.getCookie(environment.tokenKey);
    const buttons = this.tableFindModel.config.buttons;
    for (const button of buttons) {
      if (button.field === 'logOut') {
        if (CommonTool.notNull(token)) {
          button.hidden = false;
        } else {
          button.hidden = true;
        }
      } else if (button.field === 'save') {
        if (CommonTool.notNull(token)) {
          if (this.currentUser.id === this.userId) {
            button.hidden = true;
          } else {
            button.hidden = false;
          }
        } else {
          button.hidden = true;
        }
      } else if (button.field === 'home') {
        if (CommonTool.notNull(token)) {
          button.hidden = false;
        } else {
          button.hidden = true;
        }
      } else if (button.field === 'login') {
        if (!CommonTool.notNull(token)) {
          button.hidden = false;
        } else {
          button.hidden = true;
        }
      }
    }
  }


  /**
   * 保存目录及文件
   */
  public saveFolderFile() {
    this.appService.setLoading(true);
    const selectedArray = this.tableFindModel.getSelectedArray();
    const fileIds = [];
    const folderIds = [];
    selectedArray.forEach(dataModel => {
      if (dataModel.isFile) {
        fileIds.push(dataModel.data.id);
      } else {
        folderIds.push(dataModel.data.id);
      }
    });
    const req = {
      fileIds,
      folderIds,
      folderId: this.selectFolder.folderId
    };
    this.fileManagementService.createCurrentUserShareFolderFile(this.shareId, req).subscribe(res => {
      this.selectFolder.isVisible = false;
      this.message.success('保存成功!');
      this.appService.setLoading(false);
    });
  }

  public playMovie(url) {
    this.videoPlay.isVisible = true;
    this.videoPlay.url = url;
  }
}
